# -*- coding: UTF-8 -*-
# @ Author : 游于艺
# @ QQ : 58012007
# @ File: zy_day16_游于艺.py
# @ Time: 2018/3/4 12:07


"""
1.写一个函数计算1 + 3 + 5 +…+97 + 99的结果
      再写一个装饰器函数, 对其装饰, 在运算之前, 新建一个文件
      然后计算结果, 最后把计算的结果写入到文件里
"""
def calculate_decorator(func):
    def decorator_inner(b_list):
        with open("calculate_result.txt","w",encoding="utf-8") as f:
            num = func(b_list)
            f.write("计算结果为："+str(num))
        # return num
    return decorator_inner
@calculate_decorator
def calculate(a_list):
    result = 0
    for num in a_list:
        result += num
    return result
    # return sum(range(1,100,2))
the_list = range(1,100,2)   #方式一
# the_list = [x for x in range(100) if x%2 !=0]     #方式二
# print(the_list)
calculate(the_list)

"""
2.写一个函数计算传入进来参数的平方, 并将结果.写一个带参数的装饰器,
       将装饰器参数传入到被包装的函数,计算并输入结果
"""
def square_decorator(x):
    def decorator_middle(func):
        def decorator_inner(num):
            print("开始结算",x*2)
            result = func(num)
            print("计算结束",x+2)
            return result
        return decorator_inner
    return decorator_middle
@square_decorator(20)
def get_square(num):
    print("正在计算")
    return num**2
result = get_square(3)
print("结果为：",result)

